package com.tensquare.user.controller;

import com.tensquare.user.pojo.Admin;
import com.tensquare.user.service.AdminService;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by WF on 2019/9/23 9:19
 */
@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService adminService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private HttpServletRequest request;
    //1.添加管理员
    @PostMapping
    public Result add(@RequestBody Admin admin){
        //1.1)添加管理员
        adminService.add(admin);
        //1.2)返回
        return new Result(true,StatusCode.OK,"添加管理员成功！");
    }
    //2.管理员登录
    @PostMapping("login")
    public Result login(@RequestBody Admin admin){
        //2.1)根据登录名查询管理员用户
        Admin ad = adminService.findByLoginname(admin);
        //登录时生成token信息
        String token = jwtUtil.createJwt(ad.getId(), admin.getLoginname(), "admin");
        //2.2)返回
        if(ad != null) {
            Map map = new HashMap<>();
            map.put("token",token);
            map.put("name",ad.getLoginname());
            return new Result(true, StatusCode.OK, "管理员登录成功！",map);
        }
        return new Result(false, StatusCode.ERROR, "管理员登录失败！");
    }
    //3.根据管理员id删除管理员
    @DeleteMapping("{adminId}")
    public Result delete(@PathVariable String adminId){
        //3.1)得到请求作用域中以claims为key的值
        Claims claims = (Claims) request.getAttribute("claims");
        //3.2)得到此对象的roles属性的值
        String roles = (String) claims.get("roles");
        //3.3)判断其值
        if(StringUtils.isNotBlank(roles) && "admin".equals(roles)){
            adminService.delete(adminId);
            return new Result(true,StatusCode.OK,"删除管理员成功！");
        }
        return new Result(false,StatusCode.ERROR,"无删除管理员权限！");
    }
}
